<?php


namespace addons\facrm\controller;


use addons\third\model\Third;

use fast\Date;
use think\addons\Controller;
use think\Exception;
use think\Response;


/**
 * 订单支付
 * @icon fa fa-circle-o
 */
class Order extends Controller
{

    protected $layout = 'default';
    protected $pay_config = [];
    protected $key = "payonline";

    public function _initialize()
    {
        parent::_initialize();
        $epayinfo = get_addon_info('epay');
        if (!$epayinfo || !$epayinfo['state']){
            $this->error(__("微信支付宝插件未安装或未启用"));
        }
        $this->view->assign("epayinfo", $epayinfo);

        $this->request->filter(['strip_tags']);
        $settingModel = new \app\admin\model\facrm\Setting();
        $this->pay_config =\addons\facrm\library\Order::getPayConfig();
        if (!$this->pay_config) {
            $this->error(__("未配置收款"));
        }
    }


    /**
     * 支付订单[收款]
     */
    public function pay()
    {


        if (!$this->pay_config['values']['online_pay']) {
            $this->error(__("未配置收款"));
        }

        //获取收款单信息
        $pay_token = $this->request->request('pay_token');//访问凭证
        if (!$pay_token) {
            $this->error(__("访问有误"));
        }
        $receivablesModel = new \app\admin\model\facrm\contract\Receivables();
        $payInfo = $receivablesModel->where('pay_token', $pay_token)->find();
        $tempvars=$payInfo->toArray();

        $check_data=\addons\facrm\library\Order::checkPay($payInfo, 'pay',$this->pay_config);
        if ($check_data['code']!=1){
            $this->error(__($check_data['msg']));
        }


        $agreement = __($this->pay_config['values']['agreement'],$tempvars);
        $this->view->assign("row", $payInfo);
        $this->view->assign("agreement", $agreement);
        $this->view->assign("title", __("支付订单"));
        return $this->view->fetch();


    }

    /**
     * 合同续费
     */
    public function renew()
    {
        //获取合同信息
        $pay_token = $this->request->request('pay_token');
        if (!$pay_token) {
            $this->error(__("访问有误"));
        }

        //判断是否开启续费功能
        if ($this->pay_config['values']['renew_pay'] != 1) {
            $this->error(__("未开启续费功能"));
        }


        $contractModel = new \app\admin\model\facrm\Contract();
        $contractInfo = $contractModel->where('renewtoken', $pay_token)->find();
        $check_data=\addons\facrm\library\Order::checkPay($contractInfo, 'renew',$this->pay_config);
        if ($check_data['code']!=1){
            $this->error(__($check_data['msg']));
        }

        //判断合同是否设定了续费单价，
        if ($contractInfo['renewmoeny']<=0){
            $contractInfo['renewmoeny']=bcdiv(($contractInfo['money']*$this->pay_config['values']['renew_percentage']),100,2);
        }
        $pay_config=$this->pay_config['values'];
        $pay_config['r_agreement'] = __($pay_config['r_agreement'], $contractInfo->toArray());


        $this->view->assign("pay_config", $pay_config);
        $this->view->assign("row", $contractInfo);
        $this->view->assign("title", __("续费"));
        return $this->view->fetch();

    }


    /**
     * 提交支付订单
     * @return \addons\epay\library\Collection|\addons\epay\library\RedirectResponse|\addons\epay\library\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function submit()
    {
        $pay_token = request()->request('pay_token');
        if (!$pay_token) $this->error("付款单不存在");

        $info = get_addon_info('epay');
        if (!$info || !$info['state']) {
            $this->error('请在后台插件管理安装微信支付宝整合插件后重试');
        }
        $paytype = $this->request->request('paytype', 'wechat');
        $ordertype = $this->request->request('ordertype', 'pay');
        $method = $this->request->request('method');
        $appid = $this->request->request('appid');//APP的应用ID
        $returnurl = $this->request->request('returnurl', '', 'trim');
        $number = $this->request->request('number', '1', 'intval');//下单数量，只有续费才有效果


        //公众号和小程序
        $openid = '';
        if (in_array($method, ['miniapp', 'mp'])) {
            $third = Third::where('platform', 'wechat')->where('apptype', $method)->where('user_id', $this->auth->id)->find();
            if (!$third) {
                $this->error("未找到登录用户信息", 'bind');
            }
            $openid = $third['openid'];
        }
        try {
            $response = \addons\facrm\library\Order::submit($pay_token, $ordertype,$paytype, $method, $openid, $appid, $returnurl, ['number' => $number]);
            return $response;
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }

    }

    /**
     * 企业支付通知和回调
     */
    public function epay()
    {
        \think\Log::write(isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '_________', 'error');

        $type = $this->request->param('type');
        $paytype = $this->request->param('paytype');
        if ($type == 'notify') {
            \think\Log::write('__验证开始__', 'error');
            $pay = \addons\epay\library\Service::checkNotify($paytype);
            if (!$pay) {
                \think\Log::write('__签名错误_', 'error');
                echo '签名错误';
                return;
            }
            $data = $pay->verify();

           /* //调试
            $data=array(
                'total_amount'=>800,
                'out_trade_no'=>'20220519113008000000003943',
                'total_fee'=>80000,
            );*/
            try {
                $payamount = $paytype == 'alipay' ? $data['total_amount'] : $data['total_fee'] / 100;
                \think\Log::write('__进入支付_', 'error');
                \addons\facrm\library\Order::settle($data['out_trade_no'], $payamount);
            } catch (Exception $e) {
                \think\Log::write($e->getMessage() . '__支付异常报错_', 'error');
            }
           echo $pay->success();
        } else {
            $pay = \addons\epay\library\Service::checkReturn($paytype);
            if (!$pay) {
                $this->error('签名错误');
            }
            //微信支付没有返回链接
            if ($pay === true) {
                $this->success("请返回网站查看支付状态!", "");
            }

            //你可以在这里定义你的提示信息,但切记不可在此编写逻辑
            $this->success("请返回网站查看支付状态!", url("user/index"));
        }
        return;
    }


    /**
     * 生成二维码
     */
    public function qrcode()
    {
        $text = $this->request->get('text', 'hello world');

        //如果有安装二维码插件，则调用插件的生成方法
        if (class_exists("\addons\qrcode\library\Service") && get_addon_info('qrcode')['state']) {
            $qrCode = \addons\qrcode\library\Service::qrcode(['text' => $text]);
            $response = Response::create()->header("Content-Type", "image/png");

            header('Content-Type: ' . $qrCode->getContentType());
            $response->content($qrCode->writeString());
            return $response;
        } else {
            $qr = \addons\facrm\library\QRCode::getMinimumQRCode($text);
            $im = $qr->createImage(8, 5);
            header("Content-type: image/png");
            imagepng($im);
            imagedestroy($im);
            return;
        }
    }


}
